Page({
  data: {
    tempImage: "",
    name: "",
    price: "",
    description: "",
    categoryIndex: 0,
    categories: [
      { id: 1, name: "米饭套餐" },
      { id: 2, name: "面食类" },
      { id: 3, name: "小炒类" },
      { id: 4, name: "汤类" },
      { id: 5, name: "小菜" },
      { id: 6, name: "饮品" },
    ],
    tags: [
      { id: 1, name: "热销", selected: false },
      { id: 2, name: "新品", selected: false },
      { id: 3, name: "套餐", selected: false },
      { id: 4, name: "推荐", selected: false },
      { id: 5, name: "特惠", selected: false },
    ],
  },

  onLoad(options) {
    // 如果是编辑模式，获取菜品信息
    if (options.id) {
      this.getDishInfo(options.id);
    }
  },

  // 获取菜品信息
  getDishInfo(id) {
    // TODO: 调用接口获取菜品详情
    const dishInfo = {
      id: 1,
      name: "红烧肉饭",
      price: 12.0,
      description: "精选五花肉，配以土豆胡萝卜，搭配时令青菜",
      image: "/images/dishes/hongshaorou.jpg",
      categoryId: 1,
      tags: [1, 4],
    };

    // 设置表单数据
    this.setData({
      tempImage: dishInfo.image,
      name: dishInfo.name,
      price: dishInfo.price,
      description: dishInfo.description,
      categoryIndex: this.data.categories.findIndex(
        (item) => item.id === dishInfo.categoryId
      ),
      tags: this.data.tags.map((tag) => ({
        ...tag,
        selected: dishInfo.tags.includes(tag.id),
      })),
    });
  },

  // 上传图片
  handleUploadImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        // 获取图片临时路径
        const tempFilePath = res.tempFilePaths[0];

        // 显示上传中
        wx.showLoading({
          title: "上传中...",
        });

        // TODO: 调用上传接口
        setTimeout(() => {
          this.setData({
            tempImage: tempFilePath,
          });
          wx.hideLoading();
        }, 1000);
      },
    });
  },

  // 输入菜品名称
  inputName(e) {
    this.setData({
      name: e.detail.value,
    });
  },

  // 输入价格
  inputPrice(e) {
    this.setData({
      price: e.detail.value,
    });
  },

  // 输入描述
  inputDescription(e) {
    this.setData({
      description: e.detail.value,
    });
  },

  // 选择分类
  handleCategoryChange(e) {
    this.setData({
      categoryIndex: e.detail.value,
    });
  },

  // 切换标签
  toggleTag(e) {
    const id = e.currentTarget.dataset.id;
    const tags = this.data.tags.map((tag) => {
      if (tag.id === id) {
        return { ...tag, selected: !tag.selected };
      }
      return tag;
    });
    this.setData({ tags });
  },

  // 表单验证
  validateForm() {
    const { tempImage, name, price, description, categoryIndex } = this.data;

    if (!tempImage) {
      wx.showToast({
        title: "请上传菜品图片",
        icon: "none",
      });
      return false;
    }

    if (!name) {
      wx.showToast({
        title: "请输入菜品名称",
        icon: "none",
      });
      return false;
    }

    if (!price) {
      wx.showToast({
        title: "请输入价格",
        icon: "none",
      });
      return false;
    }

    if (!description) {
      wx.showToast({
        title: "请输入菜品描述",
        icon: "none",
      });
      return false;
    }

    return true;
  },

  // 提交表单
  handleSubmit() {
    if (!this.validateForm()) return;

    const {
      tempImage,
      name,
      price,
      description,
      categoryIndex,
      categories,
      tags,
    } = this.data;

    // 构建提交数据
    const submitData = {
      image: tempImage,
      name,
      price: Number(price),
      description,
      categoryId: categories[categoryIndex].id,
      tags: tags.filter((tag) => tag.selected).map((tag) => tag.id),
    };

    wx.showLoading({
      title: "保存中...",
    });

    // TODO: 调用保存接口
    console.log("提交数据：", submitData);

    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: "保存成功",
        icon: "success",
        duration: 2000,
        success: () => {
          setTimeout(() => {
            // 返回上一页并刷新
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            prevPage.getMenuList();
            wx.navigateBack();
          }, 2000);
        },
      });
    }, 1000);
  },
});
